package controller

import (
	"AccessAdmin/api/backend"
	"AccessAdmin/internal/consts"
	"AccessAdmin/internal/model"
	"AccessAdmin/internal/service"
	"context"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

var Login = cLogin{}

type cLogin struct{}

func (c *cLogin) Index(ctx context.Context, req *backend.LoginIndexReq) (res *backend.LoginIndexRes, err error) {
	service.View().Render(ctx, model.View{})
	return
}

// Login 登录
func (c *cLogin) Login(ctx context.Context, req *backend.LoginDoReq) (res *backend.LoginDoRes, err error) {
	loginLog := model.UserLoginLogInput{
		Username:     req.Username,
		LoginIp:      g.RequestFromCtx(ctx).GetClientIp(),
		LoginBrowser: req.LoginBrowser,
		LoginDevice:  req.LoginDevice,
	}
	res = &backend.LoginDoRes{}
	if !service.Captcha().VerifyAndClear(g.RequestFromCtx(ctx), consts.CaptchaDefaultName, req.Captcha) {
		loginLog.Remark = "登录失败，验证码错误！"
		_ = service.User().LoginLog(ctx, loginLog)
		return res, gerror.NewCode(gcode.CodeBusinessValidationFailed, "请输入正确的验证码")
	}
	err = service.User().Login(ctx, model.UserLoginInput{
		Username:     req.Username,
		Password:     req.Password,
		LoginBrowser: req.LoginBrowser,
		LoginDevice:  req.LoginDevice,
	})
	if err != nil {
		loginLog.Remark = "登录失败，" + err.Error()
		_ = service.User().LoginLog(ctx, loginLog)
		return
	}
	user := service.Session().GetUser(ctx)
	loginLog.IsSuccess = true
	loginLog.Remark = "登录成功"
	loginLog.UserId = user.Id
	_ = service.User().LoginLog(ctx, loginLog)
	// 识别并跳转到登录前页面
	loginReferer := service.Session().GetLoginReferer(ctx)
	if loginReferer != "" {
		_ = service.Session().RemoveLoginReferer(ctx)
	}
	res.Referer = loginReferer
	routes, _ := service.Session().GetRoutes(ctx)
	for _, item := range routes {
		res.AuthList = append(res.AuthList, item.Permission)
	}
	return
}
